﻿using System;
using System.Threading.Tasks;

namespace XCI.Core
{
    /// <summary>
    /// 互斥状态
    /// </summary>
    public class MutexStatus
    {
        private bool isBegin;
        public bool IsBegin => isBegin;

        public void Begin()
        {
            isBegin = true;
        }

        public void End()
        {
            isBegin = false;
        }

        public void Begin(Action callback)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));
            try
            {
                isBegin = true;
                callback?.Invoke();
            }
            finally
            {
                isBegin = false;
            }
        }

        public void End(Action callback)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));
            if (isBegin == false)
            {
                callback?.Invoke();
            }
        }

        public async Task BeginAsync(Func<Task> callback)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));
            try
            {
                isBegin = true;
                await callback.Invoke();
            }
            finally
            {
                isBegin = false;
            }
        }

        public async Task EndAsync(Func<Task> callback)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));
            if (isBegin == false)
            {
                await callback.Invoke();
            }
        }
    }
}